﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Syspetro.Deploy.Middleware
{
    /// <summary>
    /// 中间件
    /// 记录请求和响应数据
    /// </summary>
    public class RequestMiddleware
    {

        private readonly RequestDelegate _next;

        /// <summary>
        /// 日志接口
        /// </summary>
        private ILogger<RequestMiddleware> _logger;

        private Stopwatch _stopwatch;

        public RequestMiddleware(RequestDelegate next, ILogger<RequestMiddleware> logger)
        {
            _stopwatch = new Stopwatch();
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(Microsoft.AspNetCore.Http.HttpContext context)
        {
            // 过滤，只有接口
            var path = context.Request.Path.Value.ToLower();
            if (path.Contains("auth")|| path.Contains("wallet")|| path.Contains("mall")|| path.Contains("team"))
            {
                context.Request.EnableBuffering();
                Stream originalBody = context.Response.Body;

                _stopwatch.Restart();

                // 获取 Api 请求内容
                var requestContent = await GetRequesContent(context);

                // 获取 Api 返回内容
                using (var ms = new MemoryStream())
                {
                    context.Response.Body = ms;

                    await _next(context);
                    ms.Position = 0;
                    var responseReader = new StreamReader(ms);

                    ms.Position = 0;

                    await ms.CopyToAsync(originalBody);

                }

                context.Response.Body = originalBody;
                _stopwatch.Stop();

                var eventInfo = $"客户端IP:{context.Connection.RemoteIpAddress}请求方式：{ context.Request.Method} 请求地址：{context.Request.Scheme }://{ context.Request.Host+ context.Request.Path+ context.Request.QueryString} 请求内容：{requestContent}  耗时：{_stopwatch.ElapsedMilliseconds}ms 响应码：{context.Response.StatusCode}";/*响应内容：{responseContent}*/


                _logger.LogInformation(eventInfo);
            }
            else
            {
                await _next(context);
            }
        }

        private async Task<string> GetRequesContent(Microsoft.AspNetCore.Http.HttpContext context)
        {
            var request = context.Request;
            var sr = new StreamReader(request.Body);

            var content = $"{await sr.ReadToEndAsync()}";

            if (!string.IsNullOrEmpty(content))
            {
                request.Body.Position = 0;
            }

            return content;
        }
        private async Task<string> GetResponseContent(MemoryStream context)
        {
            var sr = new StreamReader(context);

            var content = $"{await sr.ReadToEndAsync()}";

            return content;
        }
    }
}

